/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * http://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */
package com.dian.modules.sale.service.impl;

import com.dian.common.exception.RRException;
import com.dian.common.utils.*;
import com.dian.common.validator.ValidatorUtils;
import com.dian.common.validator.group.AddGroup;
import com.dian.common.validator.group.UpdateGroup;
import com.dian.modules.enums.sale.GaugeSheet_GaugeStateEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.collections.CollectionUtils;
import cn.hutool.core.util.StrUtil;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.dian.common.server.CommonService;
import com.dian.modules.sale.dao.GaugeSheetDao;
import com.dian.modules.sale.entity.GaugeSheetEntity;
import com.dian.modules.sale.service.GaugeSheetService;
import com.dian.modules.sale.vo.GaugeSheetExportVO;

/**
 * 量尺单服务实现类
 *
 * @author xiaolai
 * @email xiaolai@9dyun.cn
 * @date 2019-06-21 10:19:58
 */
@Service("gaugeSheetService")
public class GaugeSheetServiceImpl extends ServiceImpl<GaugeSheetDao, GaugeSheetEntity> implements GaugeSheetService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public CommonService commonService;


    /**
     * 量尺单分页
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<GaugeSheetEntity> page = this.page(new Query<GaugeSheetEntity>().getPage(params),getQueryWrapper(params) );
        return new PageUtils(page);
    }

    /**
     *  量尺单新增
     * @param gaugeSheetEntity
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveInfo(GaugeSheetEntity gaugeSheetEntity) {

        //设置编码，等基础默然初始化数据设置
        //数据完整性校验
        this.paramsCheck(gaugeSheetEntity,AddGroup.class);

        //保存
        this.save(gaugeSheetEntity);

        return true;
    }

    /**
     *量尺单更新
     * @param gaugeSheetEntity
     * @return
     */
    @Override
    public boolean updateInfo(GaugeSheetEntity gaugeSheetEntity) {

        //修改状态校验
        this.updateCheck(gaugeSheetEntity.getId());

        //主表数据完整性校验
        this.paramsCheck(gaugeSheetEntity, UpdateGroup.class);

        //更新主表
        this.updateById(gaugeSheetEntity);


        return true;
    }

    /**
     *量尺单删除
     * @param ids
     * @return
     */
    @Override
    public boolean deleteInfo(Long[] ids) {

        //删除状态校验
        this.deleteCheck(ids);

        //更新主表
        this.remove(new QueryWrapper<GaugeSheetEntity>().in("id",ids));

        return true;
    }

    /**
     * 量尺单详情
     * @param id
     * @return
     */
    @Override
    public GaugeSheetEntity getInfo(Long id) {
        GaugeSheetEntity gaugeSheetEntity =getById(id);
        return gaugeSheetEntity;
    }

    /**
     * 量尺单审核
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean checkInfo(Long id) {
        GaugeSheetEntity gaugeSheetEntity =this.getById(id);
        checkCheck(gaugeSheetEntity);
        gaugeSheetEntity.setGaugeState(GaugeSheet_GaugeStateEnum.AUDITED.getValue());
        //gaugeSheetEntity.setOrderDate(new Date());
        ///gaugeSheetEntity.setCheckUserId(commonService.getUserId());
        //gaugeSheetEntity.setCheckUserName(commonService.getUserName());
        return this.updateById(gaugeSheetEntity);
    }

    /**
     *量尺单当前页or全部导出
     * @param params
     * @return
     */
    @Override
    public List<GaugeSheetExportVO> exportList(Map<String, Object> params) {
        List<GaugeSheetEntity> list;
        Integer exprotType= PUtil.getParaToInt(params.get("exprotType"),0);
        if(exprotType==0){
            list= this.page(new Query<GaugeSheetEntity>().getPage(params),getQueryWrapper(params)).getRecords();
        }else{
            list= this.list(getQueryWrapper(params));
        }

        List<GaugeSheetExportVO> resultList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)) {
            resultList = BeanConverter.convertList(list, GaugeSheetExportVO.class);
        }
        return resultList;
    }



    /***********************************************************************************************/
    /****************************************** 私有方法 ********************************************/
    /***********************************************************************************************/

    /**
     * 修改状态校验
     *
     * @param
     */
    private void updateCheck(Long id) {
        GaugeSheetEntity gaugeSheetEntity =this.getById(id);
        if(gaugeSheetEntity.getGaugeState().equals(GaugeSheet_GaugeStateEnum.AUDITED.getValue())){
            throw new RRException(String.format("量尺单已审核,禁止修改"));
        }
    }
    /**
     * 审核状态校验
     *
     * @param
     */
    private void checkCheck(GaugeSheetEntity gaugeSheetEntity) {
        if(gaugeSheetEntity.getGaugeState().equals(GaugeSheet_GaugeStateEnum.AUDITED.getValue())){
            throw new RRException(String.format("此量尺单已审核"));
        }
    }

    /**
     * 删除状态校验
     *
     * @param ids
     */
    private void deleteCheck(Long[] ids) {
        for (Long id:ids) {
                GaugeSheetEntity gaugeSheetEntity = this.getById(id);
            if(gaugeSheetEntity.getGaugeState().equals(GaugeSheet_GaugeStateEnum.AUDITED.getValue())){
                throw new RRException(String.format("已审核的量尺单，禁止删除"));
            }
        }

    }

    /**
     * 新增和修改参数校验
     *
     * @param record
     */
    private void paramsCheck(GaugeSheetEntity record, Class<?> cls) {
        ValidatorUtils.validateEntity(record, cls);
    }
    /**
     * 获取查询条件
     *
     * @param
     */
    private QueryWrapper<GaugeSheetEntity> getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<GaugeSheetEntity> queryWrapper=new QueryWrapper<>();
        if(!StrUtil.isBlankIfStr(params.get("probNo"))){
            queryWrapper.likeLeft("prob_no",params.get("probNo"));
        }
        if(!StrUtil.isBlankIfStr(params.get("gaugeDate"))){
            String gaugeDate=String.valueOf(params.get("gaugeDate"));
            String[] gaugeDateRange=gaugeDate.split("至");
            if(gaugeDateRange.length==2){
                queryWrapper.gt("gauge_date",DateUtils.getBeginTimeOfDate(gaugeDateRange[0]));
                queryWrapper.lt("gauge_date",DateUtils.getBeginTimeOfDate(gaugeDateRange[1]));
            }else{
                queryWrapper.gt("gauge_date",DateUtils.getBeginTimeOfDate(gaugeDate));
            }
        }
        if(!StrUtil.isBlankIfStr(params.get("estDate"))){
            String estDate=String.valueOf(params.get("estDate"));
            String[] estDateRange=estDate.split("至");
            if(estDateRange.length==2){
                queryWrapper.gt("est_date",DateUtils.getBeginTimeOfDate(estDateRange[0]));
                queryWrapper.lt("est_date",DateUtils.getBeginTimeOfDate(estDateRange[1]));
            }else{
                queryWrapper.gt("est_date",DateUtils.getBeginTimeOfDate(estDate));
            }
        }
        if(!StrUtil.isBlankIfStr(params.get("probId"))){
            queryWrapper.eq("prob_id",params.get("probId"));
        }
        queryWrapper.orderByAsc("id");
        return queryWrapper;
    }
}
